﻿//********************************************************************************//
//创建日期：<创建日期，2016-4-12>
//页面创建：<孙雪婷，sunxueting@shanghai3h.com>
//后台逻辑：<张晨斐，zhangchenfei@shanghai3h.com>
//功能说明：托收到账
//********************************************************************************//
using System;
using System.Data;
using System.Text;
using Web.Class;
using BLL;
using BLL.Access;
using Entity;
using System.IO;

namespace Web.Pages.YongShui._7.ZhangWuGL
{
    public partial class TuoShouDZ : BasePage
    {
        #region 属性
        /// <summary>
        /// 获取银行批量代理汇总记录
        /// </summary>
        private DataTable dtSourceYHHPHZ
        {
            get
            {
                return ViewState["dtSourceYHHPHZ"] as DataTable;
            }
            set
            {
                ViewState["dtSourceYHHPHZ"] = value;
            }
        }
        #endregion
        #region 变量
        /// <summary>
        /// 银行批量回盘汇总类
        /// </summary>
        private YS_ZW_YINHANGHPHZBLL _YS_ZW_YINGHANGHPHZBLL = new YS_ZW_YINHANGHPHZBLL();
        /// <summary>
        /// 数据访问操作类
        /// </summary>
        private SpHelper _spHelper = new SpHelper();
        private BLL.SqlHelper _splHelper = new BLL.SqlHelper();

        #endregion

        #region 事件
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                InitData();
            }
        }
        /*
        protected void btnDaoRuWJ_Click(object sender, EventArgs e)
        {
            string _ErrMsg = CheckFile();
            if (!string.IsNullOrEmpty(_ErrMsg))
            {
                PageTools.AlertMsg(this, _ErrMsg);
                return;
            }
            string _FileName = Session["_YinHangHPWJM"].ToString();
            PageTools.ConfirmMsg(this, "确认要导入回盘文件【" + _FileName + "】吗？", "btnDaoRuWJFact");
        }

        protected void btnDaoRuWJFact_Click(object sender, EventArgs e)
        {
            string _ErrMsg = YinHangHuiPanDR();
            if (!string.IsNullOrEmpty(_ErrMsg))
            {
                PageTools.AlertMsg(this, "回盘文件导入失败！原因：" + _ErrMsg);
                return;
            }
            else
            {
                PageTools.AlertMsg(this, "回盘文件导入成功！");
                InitData();
            }
        }
         * */
        protected void UpLoadFile_FileUploadComplete(object sender, DevExpress.Web.FileUploadCompleteEventArgs e)
        {
            CallbackResult cr = new CallbackResult("upload");
            int? rsno = -1;
            string rsmsg = "";
            if ((this.UpLoadFile.UploadedFiles[0].IsValid) && (this.UpLoadFile.UploadedFiles.Length > 0))
            {
                string filename = this.UpLoadFile.UploadedFiles[0].FileName;
                DataTable dt = _YS_ZW_YINGHANGHPHZBLL.SelectYS_ZW_YINHANGHPHZsDynamic("I_JLZT = 0 AND S_WENJIANM = '" + filename + "'", "");
                if ((dt != null) && (dt.Rows.Count > 0))
                {
                    cr.IsSuccess = false;
                    cr.IsAlertMsg = true;
                    cr.Msg = "该文件已做过回盘处理，请重新选择文件！";
                    e.CallbackData = cr.ToString();
                    return;
                }
                string filepath = Path.Combine(Server.MapPath("/UpLoad/YINHANGWJ/HUIPAN/"), filename);
                //将txt文件内容存至临时表
                _splHelper.DeleteFromTable("YS_TEMP_YINHANGHPWB", "where S_WENJIANM = '" + filename + "'");
                dt = new DataTable();
                dt.Columns.Add("S_WENJIANM");
                dt.Columns.Add("S_WENJIANNR");
                dt.Columns.Add("I_HUIZONGH");
                dt.Columns.Add("I_YM");
                dt.Columns.Add("N_JINE");
                dt.Columns.Add("S_YONGHUH");
                dt.Columns.Add("S_HETONGH");
                dt.Columns.Add("S_JIEGUODM");
                dt.Columns.Add("S_JIEGUOMX");
                if (!System.IO.Directory.Exists(Server.MapPath("/UpLoad/YINHANGWJ/HUIPAN/")))
                {
                    System.IO.Directory.CreateDirectory(Server.MapPath("/UpLoad/YINHANGWJ/HUIPAN/"));
                }
                this.UpLoadFile.UploadedFiles[0].SaveAs(filepath);
                FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.None);

                StreamReader sr = new StreamReader(fs, Encoding.Default);
                string _LineStr = sr.ReadLine();
                int _RowNum = 0;
                string[] contents;
                decimal huizongje = 0;
                int huizongbs = 0;
                DateTime riqi = DateTime.Now;
                while (!string.IsNullOrEmpty(_LineStr))
                {
                    DataRow dr = dt.NewRow();
                    dr["S_WENJIANNR"] = _LineStr;
                    dr["S_WENJIANM"] =filename;
                    _RowNum++;
                 
                    contents = _LineStr.Split(new string[]{" "},StringSplitOptions.RemoveEmptyEntries);
                    if (contents.Length >= 7)
                    {
                        if (_RowNum == 1)
                        {
                            dr["I_HUIZONGH"] = 1;
                            riqi = new DateTime(int.Parse(contents[2].Substring(0, 4)), int.Parse(contents[2].Substring(4, 2)), int.Parse(contents[2].Substring(6, 2)));
                            huizongje = Convert.ToDecimal(contents[3]);
                            huizongbs = Convert.ToInt32(contents[4]);
                        }
                        else
                        {
                            dr["I_HUIZONGH"] = 0;
                            dr["I_YM"] = "20" + contents[6].Substring(0, 4);
                            dr["N_JINE"] = Convert.ToDecimal(contents[3]) / 100;
                            dr["S_YONGHUH"] = contents[6].Substring(contents[6].IndexOf("加价") + 2, 7);
                            dr["S_HETONGH"] = contents[5];
                            dr["S_JIEGUODM"] = contents[4].Substring(0, 4);                            
                            //dr["S_JIEGUOMX"] = string.Join(" ", contents[6], contents[7], contents[8], contents.Length >= 10 ? contents[9] : ""); COMMENT BY GUODENGJIE 20171025
                            dr["S_JIEGUOMX"] = contents[4].Length > 4 ? contents[4].Substring(4).Replace("-","") : "";
                        }
                        dt.Rows.Add(dr);
                    }
                    _LineStr = sr.ReadLine();
                }
                if (_RowNum <= 1)
                {
                    cr.Msg = "文件明细为空，无法导入！";
                    cr.IsSuccess = false;
                    cr.IsAlertMsg = true;
                    e.CallbackData = cr.ToString();
                    return;
                }
                else if (BusinessTool.InsertOracelData(dt, "YS_TEMP_YINHANGHPWB"))
                {
                    _spHelper.P_YS_ZW_YINHANGHPDR(filename, LoginInfo.CurrentUser.UserID, huizongbs, huizongje, riqi, out rsno, out rsmsg);
                    cr.IsSuccess = (rsno==1);
                    cr.Msg = rsmsg;
                    cr.IsAlertMsg = true;
                    e.CallbackData = cr.ToString();
                    return;
                }
                else
                {
                    cr.Msg = "文件导入失败";
                    cr.IsSuccess = false;
                    cr.IsAlertMsg = true;
                    e.CallbackData = cr.ToString();
                    return;
                }
            }
        }

        #endregion
        #region 私有方法
        private void InitData()
        {
            this.dtSourceYHHPHZ = _YS_ZW_YINGHANGHPHZBLL.SelectYS_ZW_YINHANGHPHZsDynamic("I_JLZT = 0", "I_ZWYM DESC");
            this.gvXiangXiXX.DataSource = this.dtSourceYHHPHZ;
            this.gvXiangXiXX.DataBind();
        }

        private string CheckFile()
        {
            string _ErrMsg = "";
            string _FileName = Session["_YinHangHPWJM"].ToString();
            string _FilePath = Session["_YinHangHPWJLJ"].ToString();
            if (string.IsNullOrEmpty(_FileName) || string.IsNullOrEmpty(_FilePath))
            {
                _ErrMsg = "上传文件失败，请重新选择文件进行上传！";
            }
            else
            {

                DataTable dt = _YS_ZW_YINGHANGHPHZBLL.SelectYS_ZW_YINHANGHPHZsDynamic("I_JLZT = 0 AND S_WENJIANM = '" + _FileName + "'", "");
                if ((dt != null) && (dt.Rows.Count > 0))
                {
                    _ErrMsg = "该文件已做过回盘处理，请重新选择文件！";
                }
            }
            return _ErrMsg;
        }

        protected void gvXiangXiXX_CustomCallback(object sender, DevExpress.Web.ASPxGridViewCustomCallbackEventArgs e)
        {
            this.InitData();
        }

      
        /*
        private bool UploadFileToServer()
        {
            bool _success = true;
            string _FileName = this.UpLoadFile.FileName;
            string _ServerPath = Path.Combine(Server.MapPath("/UpLoad/YINHANGWJ/HUIPAN/"), _FileName);
            try
            {
                this.UpLoadFile.SaveAs(_ServerPath);
                Session["_YinHangHPWJM"] = _FileName;
                Session["_YinHangHPWJLJ"] = _ServerPath;
            }
            catch
            {
                Session["_YinHangHPWJM"] = "";
                Session["_YinHangHPWJLJ"] = "";
                _success = false;
            }
            return _success;
        }
        */

        /*
        private string YinHangHuiPanDR()
        {
            this.ucDaoRuWJ.Enabled = false;
            //this.btnDaoRuWJ.Enabled = false;
            string _ErrMsg = "";
            string _FileName = Session["_YinHangHPWJM"].ToString();
            string _FilePath = Session["_YinHangHPWJLJ"].ToString();
            //try
            //{
            //将txt文件内容存至临时表
            DataTable dt = new DataTable();
            dt.Columns.Add("S_WENJIANM");
            dt.Columns.Add("S_WENJIANNR");
            dt.Columns.Add("I_HUIZONGH");
            dt.Columns.Add("I_YM");
            dt.Columns.Add("N_JINE");
            dt.Columns.Add("S_YONGHUH");
            dt.Columns.Add("S_JIEGUODM");
            dt.Columns.Add("S_JIEGUOMX");
            FileStream _fs = new FileStream(_FilePath, FileMode.Open, FileAccess.Read, FileShare.None);
            StreamReader _sr = new StreamReader(_fs, Encoding.Default);
            string _LineStr = _sr.ReadLine();
            int _RowNum = 0;
            string[] contents;
            decimal huizongje = 0;
            int huizongbs = 0;
            DateTime riqi = DateTime.Now;
            while (!string.IsNullOrEmpty(_LineStr))
            {
                DataRow dr = dt.NewRow();
                dr["S_WENJIANNR"] = _LineStr;
                dr["S_WENJIANM"] = _FileName;
                _RowNum++;

                //将多空格替换成单空格
                while (_LineStr.IndexOf("  ") != -1)
                {
                    _LineStr = _LineStr.Replace("  ", " ");
                    _LineStr = _LineStr.Replace("　　", " ");
                    _LineStr = _LineStr.Replace(" 　", " ");
                    _LineStr = _LineStr.Replace("　 ", " ");
                }
                contents = _LineStr.Split(' ');
                if (contents.Length >= 7)
                {
                    if (_RowNum == 1)
                    {
                        dr["I_HUIZONGH"] = 1;
                        riqi = new DateTime(int.Parse(contents[2].Substring(0, 4)), int.Parse(contents[2].Substring(4, 2)), int.Parse(contents[2].Substring(6, 2)));
                        huizongje = Convert.ToDecimal(contents[3]);
                        huizongbs = Convert.ToInt32(contents[4]);
                    }
                    else
                    {
                        dr["I_HUIZONGH"] = 0;
                        dr["I_YM"] = "20" + contents[6].Substring(0, 4);
                        dr["N_JINE"] = Convert.ToDecimal(contents[3]) / 100;
                        dr["S_YONGHUH"] = contents[6].Substring(contents[6].IndexOf("加价") + 2, 7);
                        dr["S_JIEGUODM"] = contents[4].Substring(0, 4);
                        dr["S_JIEGUOMX"] = string.Join(" ", contents[6], contents[7], contents[8], contents.Length >= 10 ? contents[9] : "");
                    }
                    dt.Rows.Add(dr);
                }
                _LineStr = _sr.ReadLine();
            }
            if (_RowNum <= 1)
            {
                _ErrMsg = "文件明细为空，无法导入！";
            }
            else if (BusinessTool.InsertOracelData(dt, "YS_TEMP_YINHANGHPWB"))
            {
                int? _ErrCode = -1;
                _spHelper.P_YS_ZW_YINHANGHPDR(Session["_YinHangHPWJM"].ToString(), LoginInfo.CurrentUser.UserID, huizongbs, huizongje, riqi, out _ErrCode, out _ErrMsg);
            }
            else
            {
                _ErrMsg = "文件导入失败";
            }
            //}
            //catch
            //{
            //    _ErrMsg = "回盘出错！";
            //}
            //finally
            //{
            Session["_YinHangHPWJM"] = "";
            Session["_YinHangHPWJLJ"] = "";
            this.ucDaoRuWJ.Enabled = true;
            //this.btnDaoRuWJ.Enabled = true;
            //}
            return _ErrMsg;
        }
        */
        #endregion

    }
}